
import audioLoader from 'audio-loader';
import fs from 'fs/promises';
import pLimit from 'p-limit';
import path from 'path';

// 并发控制（限制同时处理的文件数）
const CONCURRENCY = 5;
const limiter = pLimit(CONCURRENCY);

// 增强版配置文件读取
const loadConfig = async (configPath) => {
  try {
    const rawData = await fs.readFile(configPath);
    return JSON.parse(Buffer.from(rawData).toString().replace(/\\/g, '\\\\'));
  } catch (err) {
    throw new Error(`配置文件读取失败: ${err.message}`);
  }
};

// 改进的时长计算器
async function calculateTotalDuration(dirPath) {
  let totalSeconds = 0;
  let processedCount = 0;

  const processFile = async (filePath) => {
    try {
      const audio = await limiter(() => audioLoader(filePath));
      const duration = audio.duration || 0;
      totalSeconds += duration;
      processedCount++;
      if (processedCount % 100 === 0) {
        const { hours, minutes, seconds } = formatTime(totalSeconds);
        console.log(`已处理 ${processedCount} 个文件，当前总时长:  ${hours}小时 ${minutes}分钟 ${seconds}秒`);
      }
    } catch (e) {
      console.error(`[SKIPPED] ${path.basename(filePath)}: ${e.message}`);
    }
  };

  const processDir = async (dirPath) => {
    const entries = await fs.readdir(dirPath);
    await Promise.all(entries.map(async (entry) => {
      const fullPath = path.join(dirPath, entry);
      const stat = await fs.stat(fullPath);
      stat.isDirectory()
        ? await processDir(fullPath)
        : await processFile(fullPath);
    }));
  };

  await processDir(dirPath);
  return formatTime(totalSeconds);
}

// 时间格式化辅助函数
function formatTime(totalSeconds) {
  return {
    hours: Math.floor(totalSeconds / 3600),
    minutes: Math.floor((totalSeconds % 3600) / 60),
    seconds: Math.floor(totalSeconds % 60)
  };
}

// 执行主程序
(async () => {
  try {
    const config = await loadConfig('./config.json');
    console.log(`开始处理目录: ${config.audioFolder}`);

    const startTime = Date.now();
    const { hours, minutes, seconds } = await calculateTotalDuration(config.audioFolder);

    console.log(`\n处理完成，总时长: ${hours}小时 ${minutes}分钟 ${seconds}秒`);
    console.log(`总耗时: ${((Date.now() - startTime) / 1000).toFixed(1)}秒`);
  } catch (err) {
    console.error('程序异常终止:', err.message);
    process.exit(1);
  }
})();
